package com.shushan.mixedexam;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.mixedexam.adapter.ExamFragmentAdapter;
import com.shushan.mixedexam.bean.ExerciseResultBean;
import com.shushan.mixedexam.englishwords.EnglishWordsExam3Fragment;
import com.shushan.mixedexam.oralcalculation.OnAnswerCompleteListener;
import com.shushan.mixedexam.oralcalculation.OralCalculationExamFragment;
import com.shushan.mixedexam.oralcalculation.bean.OCExerciseResultBean;
import com.shushan.mixedexam.oralcalculation.bean.OralCalculateExamBean;
import com.shushan.mixedexam.oralcalculation.bean.OralCalculateExerciseBean;
import com.shushan.mixedexam.oralcalculation.bean.OralCalculatePaperInfoBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.AnimationsContainer;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.NoScrollViewPager;
import com.shushan.util.DownloadUtil;
import com.shushan.util.Session;
import com.shushan.util.StringTools;
import com.shushan.util.ToolUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName: OralCalculateExamActivity
 * @Desciption: //口算练习做题页面
 * @author: zhangshihao
 * @date: 2018-07-04
 */
public class OralCalculateExamActivity extends BaseActivity implements OnAnswerCompleteListener,
        ViewPager.OnPageChangeListener {

    private static final String TAG = OralCalculateExamActivity.class.getSimpleName();

    private ProgressBar pbCountBack;
    private TextView tvSeconds;
    private NoScrollViewPager examVp;
    private ExamFragmentAdapter examFragmentAdapter;
    private TextView tvCurrentNum, tvTopicTotalNum;
    private ImageView ivRight, ivWrong;
    private RelativeLayout rlPbContainer;
    private TextView tvExamRequire;

    private int specialId = 0;
    private OralCalculateExamBean examBean;

    private int totalTime = 0;//单位秒
    private int examTime = 0;//单位秒
    private int progressDelayTime;//setprogress的间隔时间
    private boolean doneFinish = false;
    private int pageIndex = 0;//当前页数
    private int needRightCount = 0;//用户需要回答正确的题数
    private int rightCount = 0;
    private int errCount = 0;

    private SoundPool soundPool;//播放短小音频
    private int[] soundResIds = {R.raw.right_audio, R.raw.wrong_audio};
    private HashMap<Integer, Integer> soundIdMap = new HashMap<>();
    private AnimationsContainer.FramesSequenceAnimation rightAnimation;
    private AnimationsContainer.FramesSequenceAnimation wrongAnimation;

    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private int jumpType = 0;
    private boolean fromRecord = false;

    Handler scrollHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    examVp.setCurrentItem(msg.arg1, true);
                    tvCurrentNum.setText("(" + (msg.arg1 + 1));
                    break;
                default:
                    break;
            }
        }
    };
    Handler handler = new Handler();
    Runnable examTimeRunnable = new Runnable() {
        @Override
        public void run() {
            if (doneFinish) {
                return;
            }
            examTime--;
            if (examTime < 0) {
                return;
            }
            tvSeconds.setText(examTime + "s");
            handler.postDelayed(this, 1000);
        }
    };
    Runnable progressRunnable = new Runnable() {
        @Override
        public void run() {
            if (doneFinish) {
                return;
            }
            if ((pbCountBack.getProgress() - 1) < 0) {
                postPaperRecord();
                return;
            }
            pbCountBack.setProgress(pbCountBack.getProgress() - 1);
            handler.postDelayed(this, progressDelayTime);
        }
    };
    private PowerManager.WakeLock wakeLock;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_oral_calculate_exam);

        ScreenManager sm = new ScreenManager();
        if(!sm.setDeepStatusBar(true,this)){
            findViewById(R.id.titlebar_divider).setVisibility(View.GONE);
        }

        examBean = (OralCalculateExamBean) Session.getSession().get("oralExamBean");
        jumpType = getIntent().getIntExtra(Constants.SCORE_RESULT_JUMP_TYPE, 0);
        fromRecord = getIntent().getBooleanExtra("fromRecord", false);

        initView();
        if (examBean != null) {
            setData(examBean);
        } else {
            getData();
        }

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "KeepScreenOn");
        wakeLock.acquire();
    }

    private int getProgressDelayTime() {
        int delayTime = 0;
        delayTime = (int) (((float) examTime / 100) * 1000);
        Log.d(TAG, "delayTime == " + delayTime);
        return delayTime;
    }

    private void initView() {
        pbCountBack = findViewById(R.id.pb_countback_seconds);
        tvSeconds = findViewById(R.id.tv_seconds);
        tvSeconds.setText(examTime + "");
        examVp = findViewById(R.id.exam_vp);
        tvCurrentNum = findViewById(R.id.tv_current_num);
        tvTopicTotalNum = findViewById(R.id.tv_topic_total_num);
        ivRight = findViewById(R.id.iv_right);
        ivWrong = findViewById(R.id.iv_wrong);
        rlPbContainer = findViewById(R.id.rl_pb_container);

        if (jumpType == Constants.JUMP_TYPE_TOPICS_WATCH || jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
            rlPbContainer.setVisibility(View.GONE);
            examVp.setScroll(true);
            examVp.addOnPageChangeListener(this);
        }

        soundPool = new SoundPool.Builder().setMaxStreams(soundResIds.length).build();
        soundIdMap.put(0, soundPool.load(this, soundResIds[0], 1));
        soundIdMap.put(1, soundPool.load(this, soundResIds[1], 1));
        initAnswerAnimation();
        tvExamRequire = findViewById(R.id.tv_exam_require);
    }

    private void initAnswerAnimation() {
        if (rightAnimation == null) {
            rightAnimation = new AnimationsContainer(R.array.loading_anim_right, 18).createProgressDialogAnim(ivRight);
            ivRight.clearAnimation();
        }

        if (wrongAnimation == null) {
            wrongAnimation = new AnimationsContainer(R.array.loading_anim_wrong, 18).createProgressDialogAnim(ivWrong);
            ivWrong.clearAnimation();
        }
    }

    private void getData() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.OC_EXERCISE);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<OralCalculateExamBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(OralCalculateExamBean oralCalculateExamBean) {
                        if (oralCalculateExamBean == null) {
                            return;
                        }
                        examBean = oralCalculateExamBean;
                        setData(oralCalculateExamBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setData(OralCalculateExamBean oralCalculateExamBean) {
        OralCalculatePaperInfoBean paperInfoBean = oralCalculateExamBean.paperInfoBean;
        boolean isOnlyDisplay = false;
        if (!(jumpType == Constants.JUMP_TYPE_TOPICS_WATCH || jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH)) {
            if (Constants.isForEditors) {
                needRightCount = Integer.MAX_VALUE;
                totalTime = Integer.MAX_VALUE;
                examTime = Integer.MAX_VALUE;
            } else if (paperInfoBean != null) {
                needRightCount = paperInfoBean.num;
                totalTime = paperInfoBean.total * 60;
                examTime = paperInfoBean.total * 60;
                tvExamRequire.setText(paperInfoBean.total + "分钟内做对" + paperInfoBean.num + "道题目");
            }
            progressDelayTime = getProgressDelayTime();
            handler.postDelayed(examTimeRunnable, 1000);
            handler.postDelayed(progressRunnable, progressDelayTime);
        } else {
            isOnlyDisplay = true;
        }

        List<OralCalculateExerciseBean> oralCalculateExerciseBeans = oralCalculateExamBean.getOralCalculateExerciseBeans();
        if (ToolUtils.isListEmpty(oralCalculateExerciseBeans)) {
            return;
        }
        List<Fragment> examFragments = new ArrayList<>();
        for (int i = 0; i < oralCalculateExerciseBeans.size(); i++) {
            OralCalculateExerciseBean exerciseBean = oralCalculateExerciseBeans.get(i);
            if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH || fromRecord) {
//                if (ToolUtils.isWrongTopic(exerciseBean,fromRecord)) {
                    OralCalculationExamFragment examFragment = OralCalculationExamFragment.newInstance(isOnlyDisplay, this, i, exerciseBean, fromRecord);
                    examFragments.add(examFragment);
//                }
            } else {
                OralCalculationExamFragment examFragment = OralCalculationExamFragment.newInstance(isOnlyDisplay, this, i, exerciseBean, fromRecord);
                examFragments.add(examFragment);
            }
        }
        tvTopicTotalNum.setText("/" + examFragments.size() + ")");
        examFragmentAdapter = new ExamFragmentAdapter(this, getSupportFragmentManager(), examFragments);
        examVp.setAdapter(examFragmentAdapter);
    }

    @Override
    public void onPageSelected(int position) {
        tvCurrentNum.setText("(" + (position + 1));
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        //do nothing
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        //do nothing
    }

    @Override
    public void onAnswerComplete(int examIndex, boolean isRight, String answer) {
        Log.i(TAG, "examIndex == " + examIndex + " ; isRight == " + isRight+" ; answer == "+answer);
        if (isRight) {
            rightCount++;
            soundPool.play(soundIdMap.get(0), 1, 1, 1, 0, 1);
            if (rightAnimation.isRunning()) {
                rightAnimation.stop();
            }
            rightAnimation.start();
        } else {
            errCount++;
            soundPool.play(soundIdMap.get(1), 1, 1, 1, 0, 1);
            if (wrongAnimation.isRunning()) {
                wrongAnimation.stop();
            }
            wrongAnimation.start();
        }

        if (examBean != null) {
            List<OralCalculateExerciseBean> exerciseBeans = examBean.getOralCalculateExerciseBeans();
            if (!ToolUtils.isListEmpty(exerciseBeans) && exerciseBeans.size() >= examIndex + 1) {
                OralCalculateExerciseBean exerciseBean = exerciseBeans.get(examIndex);
                exerciseBean.my_answer = answer;
                exerciseBean.result = isRight ? 1 : 0;
            }
        }
        if (examIndex + 1 == examFragmentAdapter.getCount()) {
            postPaperRecord();
        } else {
            Message msg = scrollHandler.obtainMessage(0);
            msg.arg1 = examIndex + 1;
            scrollHandler.sendMessage(msg);
        }
    }

    @Override
    protected void onTitleBack() {
        if (jumpType == Constants.JUMP_TYPE_TOPICS_WATCH || jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
            onBackAction();
        } else {
            showNoBackWarnDialog();
        }
    }

    private void showNoBackWarnDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("答题期间，没有答完题目，数据尚未上报，不建议退出，是否退出？")
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        finish();
                    }
                })
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();
    }

    private void postPaperRecord() {
        if (examBean == null) {
            return;
        }

        if (examBean.isNotDo()) {
            onBackAction();
            return;
        }

        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.OC_TOPIC_REPORT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("answer", getAnswerJsonArrStr())
                .putValue("time_consuming", 300);//time_consuming后台不使用，随便传
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<OCExerciseResultBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(OCExerciseResultBean ocResultBean) {
                        onBackAction();
                        if (ocResultBean == null) {
                            return;
                        }
                        gotoScoreResult(ocResultBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void gotoScoreResult(OCExerciseResultBean ocResultBean) {
        Session.getSession().put("ocResultBean", ocResultBean);
        Session.getSession().put("oralExamBean", examBean);

        Intent intent = new Intent(this, OralCalculateScoreActivity.class);
        intent.putExtra("coseTime", totalTime - examTime);
        intent.putExtra("completeTopicCount", rightCount + errCount);
        startActivityAllow(intent);
    }

    private String getAnswerJsonArrStr() {
        JSONArray jsonArray = new JSONArray();
        List<OralCalculateExerciseBean> exerciseBeans = examBean.getOralCalculateExerciseBeans();
        if (!ToolUtils.isListEmpty(exerciseBeans)) {
            for (int i = 0; i < exerciseBeans.size(); i++) {
                OralCalculateExerciseBean exerciseBean = exerciseBeans.get(i);
                if (TextUtils.isEmpty(exerciseBean.my_answer)) {
                    break;
                }
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("id", exerciseBean.id);
                    jsonObject.put("questions", exerciseBean.questions);
                    jsonObject.put("answer", exerciseBean.answer);
                    jsonObject.put("outline_detail_id", exerciseBean.outline_detail_id);
                    jsonObject.put("outline_id", exerciseBean.outline_id);
                    jsonObject.put("my_answer", exerciseBean.my_answer);
                    jsonObject.put("result", exerciseBean.result);
                    jsonArray.put(jsonObject);
                } catch (JSONException je) {
                    je.printStackTrace();
                }
            }
        }
        return jsonArray.toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doneFinish = true;

        setResult(100);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            showNoBackWarnDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
